using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Management;

namespace HGY.NetworkInterfaceManager
{
    public partial class FrmHostedNetwork : Form
    {
        private string batFile = Path.Combine(Path.GetTempPath(), "ids.bat");
        private string vbsFile = Path.Combine(Path.GetTempPath(), "ics.vbs");
        private List<NetworkAdapter> _NetworkAdapters = new List<NetworkAdapter>();
        public FrmHostedNetwork(List<NetworkAdapter> ns)
        {
            InitializeComponent();
            _NetworkAdapters = ns;
            this.comboAdapters.DataSource = _NetworkAdapters;
            this.comboAdapters.DisplayMember = "Name";
            this.comboAdapters.ValueMember = "ID";
            this.textSSID.Text = "Win7WiFiAP(" + Dns.GetHostName() + ")";
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            StringBuilder cmdText = new StringBuilder("@");
            cmdText.AppendLine("echo off");
            cmdText.AppendLine("netsh wlan stop hostednetwork");
            cmdText.AppendLine("netsh wlan set hostednetwork mode=disallow");
            cmdText.AppendLine("netsh wlan set hostednetwork mode=allow");
            cmdText.AppendFormat("netsh wlan set hostednetwork ssid={0} key={1} keyUsage=persistent", this.textSSID.Text, this.textPwd.Text);
            cmdText.AppendLine();
            cmdText.AppendLine("netsh wlan start hostednetwork");
            Common.SaveFile(batFile, cmdText.ToString());

            RunCmd(batFile, false, true);
            string tagAdapterName = QueryWiFiAdapterName();
            NetworkAdapter adp = comboAdapters.SelectedItem as NetworkAdapter;
            if (checkShare.Checked && adp != null && !string.IsNullOrEmpty(tagAdapterName))
            {
                Common.SaveFile(vbsFile, Properties.Resources.ics);
                cmdText = new StringBuilder();
                cmdText.AppendLine("@echo off");
                foreach (string s in QueryAllAdapterName())
                {
                    cmdText.AppendFormat("cscript /nologo \"%~dp0\\ics.vbs\" \"{0}\" \"{1}\" \"off\" >nul 2>nul", tagAdapterName, s);
                    cmdText.AppendLine("");
                }


                cmdText.AppendFormat("cscript /nologo \"%~dp0\\ics.vbs\" \"{0}\" \"{1}\" \"on\" >nul 2>nul", tagAdapterName, adp.Name);
                cmdText.AppendLine("");
                Common.SaveFile(batFile, cmdText.ToString());
                RunCmd(batFile, false, true);
            }
        }



        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                string tagAdapterName = QueryWiFiAdapterName();
                NetworkAdapter adp = comboAdapters.SelectedItem as NetworkAdapter;
                Common.SaveFile(vbsFile, Properties.Resources.ics);
                StringBuilder cmdText = new StringBuilder();
                cmdText.AppendLine("@echo off");
                foreach (string s in QueryAllAdapterName())
                {
                    cmdText.AppendFormat("cscript /nologo \"%~dp0\\ics.vbs\" \"{0}\" \"{1}\" \"off\" >nul 2>nul", tagAdapterName, s);
                    cmdText.AppendLine("");
                }

                cmdText.AppendLine("netsh wlan stop hostednetwork");
                cmdText.AppendLine("netsh wlan set hostednetwork mode=disallow");
                cmdText.AppendLine("");
                Common.SaveFile(batFile, cmdText.ToString());
                RunCmd(batFile, false, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        

        public string QueryWiFiAdapterName()
        {

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_NetworkAdapter");
            ManagementObjectCollection collection = searcher.Get();
            foreach (ManagementObject manage in collection)
            {
                if (manage["Name"].ToString() == "Microsoft Virtual WiFi Miniport Adapter" && manage["NetConnectionID"] != null && manage["NetConnectionID"].ToString() != string.Empty)
                {

                    return manage["NetConnectionID"].ToString();

                }
            }
            return string.Empty;
        }


        public string[] QueryAllAdapterName()
        {
            List<string> names = new List<string>();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_NetworkAdapter");
            ManagementObjectCollection collection = searcher.Get();
            foreach (ManagementObject manage in collection)
            {
                if (manage["Name"].ToString() != "Microsoft Virtual WiFi Miniport Adapter" && manage["NetConnectionID"] != null && manage["NetConnectionID"].ToString() != string.Empty)
                {
                    names.Add(manage["NetConnectionID"].ToString());

                }
            }
            return names.ToArray();
        }
        protected void RunCmd(String cmd, Boolean showWindow, Boolean waitForExit)
        {

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo();
            string path = Environment.SystemDirectory;
            path = Path.Combine(path, @"cmd.exe");
            p.StartInfo.FileName = path;
            if (!cmd.StartsWith(@"/")) cmd = @"/c " + cmd;
            p.StartInfo.Arguments = cmd;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = !showWindow;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;


            p.Start();
            if (waitForExit)
            {
                p.WaitForExit();

                string str = p.StandardOutput.ReadToEnd();
                if (!String.IsNullOrEmpty(str)) WriteLine(str.Trim(new Char[] { '\r', '\n', '\t' }).Trim());
                str = p.StandardError.ReadToEnd();
                if (!String.IsNullOrEmpty(str)) WriteLine(str.Trim(new Char[] { '\r', '\n', '\t' }).Trim());
            }
        }

        private void WriteLine(string p)
        {
            if (textMsg.Lines.Length > 100)
            {
                textMsg.Clear();
            }
            textMsg.Text += p + Environment.NewLine;
            if (textMsg.Text.Length > 5)
            {
                textMsg.SelectionLength = textMsg.Text.Length - 1;
            }
            textMsg.ScrollToCaret();
        }

        private void checkShare_CheckedChanged(object sender, EventArgs e)
        {
            comboAdapters.Enabled = checkShare.Checked;
        }

        private void menuClear_Click(object sender, EventArgs e)
        {
            textMsg.Clear();
        }
    }
}